/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.lcm.metadata.core;

import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.MetadataProject;
import com.inspur.edp.lcm.metadata.api.entity.uri.AbstractURI;
import com.inspur.edp.lcm.metadata.api.entity.uri.MetadataURI;
import com.inspur.edp.lcm.metadata.api.exception.MetadataNotFoundException;
import com.inspur.edp.lcm.metadata.cache.MdProjFileLastChangedCache;
import com.inspur.edp.lcm.metadata.cache.MetadataDevCacheManager;
import com.inspur.edp.lcm.metadata.core.exception.MetadataExceptionHandler;
import com.inspur.edp.lcm.metadata.core.index.ProjectMetadataCacheService;
import com.inspur.edp.lcm.metadata.devcommon.ManagerUtils;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhaoleitr
 */
@Slf4j
public class RefCommonCoreService {
    private final MetadataCoreManager metadataManager = new MetadataCoreManager();
    private final MetadataProjectCoreService projectService = new MetadataProjectCoreService();

    private GspMetadata getRefMetadata(String metadataId, String projectPath, MetadataProject metadataProject) {
        // 当前工程及bo下的引用的工程下搜索
        GspMetadata gspMetadata = getMetadataFromProjects(metadataId, metadataProject);
        if (gspMetadata != null) {
            return gspMetadata;
        }

        // 初始化缓存
        ProjectMetadataCacheService projectMetadataCacheService = ProjectMetadataCacheService.getNewInstance(metadataProject, projectPath);
        //缓存中获取元数据归属并构造元数据
        return projectMetadataCacheService.getRefMetadata(metadataId);
    }

    public GspMetadata getRefMetadata(MetadataURI targetURI, AbstractURI sourceURI, String projectPath) {
        // 工程信息
        projectPath = projectService.getProjPath(projectPath);
        MetadataProject metadataProject = projectService.getMetadataProjInfo(projectPath);
        try {
            return getRefMetadata(targetURI.getId(), projectPath, metadataProject);
        } catch (MetadataNotFoundException ignore) {
            // 若查找不到依赖元数据, 则清理工程下元数据列表缓存 以及 依赖引用关系图缓存后重新获取
            clearRefMetadataCache(projectPath, metadataProject);
            try {
                // 若清理缓存后仍获取不到,则抛出异常
                return getRefMetadata(targetURI.getId(), projectPath, metadataProject);
            } catch (MetadataNotFoundException e) {
                MetadataExceptionHandler.handleMetadataNotFoundException(targetURI, sourceURI, projectPath);
            }
        }
        return null;
    }

    private GspMetadata getMetadataFromProjects(String metadataID, MetadataProject metadataProject) {
        Set<String> refProjPaths = new HashSet<>();
        if (metadataProject != null) {
            refProjPaths.add(metadataProject.getProjectPath());
            projectService.getRefProjPaths(metadataProject.getProjectPath(), refProjPaths);

            for (String projPath : refProjPaths) {
                List<GspMetadata> metadataList = metadataManager.getMetadataList(projPath);
                for (GspMetadata gspMetadata : metadataList) {
                    if (gspMetadata.getHeader() != null && gspMetadata.getHeader().getId() != null && metadataID.equals(gspMetadata.getHeader().getId())) {
                        gspMetadata = metadataManager.loadMetadata(gspMetadata.getHeader().getFileName(), gspMetadata.getRelativePath());
                        return gspMetadata;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 清理工程内元数据列表缓存以及依赖引用关系图缓存
     *
     * @param projectPath     工程路径
     * @param metadataProject 元数据工程信息
     */
    private void clearRefMetadataCache(String projectPath, MetadataProject metadataProject) {
        Set<String> refProjPaths = new HashSet<>();
        if (metadataProject != null) {
            refProjPaths.add(metadataProject.getProjectPath());
            projectService.getRefProjPaths(metadataProject.getProjectPath(), refProjPaths);

            for (String projPath : refProjPaths) {
                String absolutePath = ManagerUtils.getAbsolutePath(projPath);
                MetadataDevCacheManager.removeMetadataListInProject(absolutePath);
            }
        }
        MdProjFileLastChangedCache.evict(projectPath);
    }
}
